package qf.controller;


import qf.utils.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author 86198
 * @version V1.0
 * @Project Java_qf
 * @Package qf.controller
 * @Description:
 * @Date 2022/5/20 15:27
 */
public class BaseServlet extends  HttpServlet{
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取前端传过来的method属性的值
        String methodStr = req.getParameter(Constants.TAG);
        System.out.println(methodStr);
        if (methodStr == null || "".equals(methodStr)) {
            methodStr=Constants.INDEX;
        }
        //2.获取访问对象的大Class
        Class clazz = this.getClass();
        try {
            //3.通过此类的大Class获取此方法
            Method method = clazz.getMethod(methodStr, HttpServletRequest.class, HttpServletResponse.class);

            //4.运行此方法并获取其返回值
            Object invoke = method.invoke(this, req,resp);
            ///5.根据返回的结果进行判断, 判断返回值不为空
            if (invoke != null) {
                String jump = (String)invoke;
                //判断返回值的第一个字符串为跳转还是重定向
                if (jump.startsWith(Constants.FORWARD)) {
                    //获取返回值要跳转的路径
                    String path = jump.substring(jump.indexOf(Constants.FLAG) + 1);
                    //跳转
                    req.getRequestDispatcher(path).forward(req,resp);
                }else if (jump.startsWith(Constants.REDIRECT)){
                    String path = jump.substring(jump.indexOf(Constants.FLAG) + 1);
                    resp.sendRedirect(path);
                }else {
                    resp.getWriter().println(jump);
                }
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

    }
}